"use client";
import React, { useEffect, useId, useState } from "react";
import style from "./page.module.scss";
import { Avatar, ConfigProvider, Form, message } from "antd";
import { FormOutlined } from "@ant-design/icons";
import BaseMsgForm from "@/components/BaseMsgForm";
import zhCN from "antd/locale/zh_CN";
import { getCity, getUserById, updatePerMsg, upload } from "@/api";
import { SEVER_URL } from "@/configs/constant";
import dayjs from "dayjs";
import UploadImg from "@/components/UploadImg";
import { useStore } from "@/zustand/store";

type TUserDetail = {
  id: number;
  userAccount: string;
  avotar: string;
  userAddress: string;
  userBirth: string;
  userHead: string;
  userIntroduce: string;
  userName: string;
  userSex: string;
  description: string;
  createTime: string;
  updateTime: string;
  userStatus: number;
  videoId: number;
};
export default function PersonalCenter() {
  const dateFormat = "YYYY-MM-DD";
  const [cities, setCities] = useState([]);
  const [form] = Form.useForm();
  const [loading, setLoading] = useState<boolean>(false);
  const [imgUrl, setImgUrl] = useState("");
  const [isAvatar, setIsAvatar] = useState(false);
  const [userDetail, setUserDetail] = useState<TUserDetail>({
    createTime: "",
    userBirth: "",
    userAddress: "",
  } as TUserDetail);
  const userId = useStore((state) => state.userId);
  const getCities = async () => {
    const res = await getCity();
    res.data.code === 200 && setCities(res.data.data);
  };
  const initUserInfo = async () => {
    setLoading(true);
    const res = await getUserById({
      id: userId,
    });
    if (res.data.code === 200) {
      setUserDetail(res.data.data);
      res.data.data.userHead && setImgUrl(`${res.data.data.userHead}`);
      setLoading(false);
      form.setFieldsValue({
        userName: res.data.data.userName,
        userIntroduce: res.data.data.userIntroduce,
        userAddress:
          res.data.data.userAddress && res.data.data.userAddress.split(","),
        userBirth:
          res.data.data.userBirth &&
          dayjs(`${res.data.data.userBirth}`, dateFormat),
      });
    }
  };
  const handleUploadAvator = async (e: React.ChangeEvent<HTMLInputElement>) => {
    setLoading(true);
    if (e.target.files) {
      const files = e.target.files[0];
      var formData = new FormData();
      formData.append("files", files);
      const response = await upload(formData);
      if (response.data.code === 200) {
        setImgUrl(response.data.data[0]);
        const res = await updatePerMsg({
          userHead: response.data.data[0],
          id: userId,
        });
        if (res.data.code === 200) {
          setLoading(false);
          setIsAvatar(false);

          message.success(res.data.msg);
        }
      } else {
        message.error(response.data.msg);
      }
    }
  };
  useEffect(() => {
    initUserInfo();
    getCities();
  }, []);

  return (
    <ConfigProvider locale={zhCN}>
      <div className={style["personnalCenterContainer"]}>
        <div className={style["personnalCenterContent"]}>
          <div className={style["header"]}>
            <div
              className={style["avatar"]}
              onMouseEnter={() => setIsAvatar(true)}
              onMouseLeave={() => setIsAvatar(false)}
            >
              {isAvatar && (
                <UploadImg
                  isLoading={loading}
                  onChange={handleUploadAvator}
                  className={style["avatarCircle"]}
                ></UploadImg>
              )}
              <Avatar
                src={imgUrl ? `${SEVER_URL}${imgUrl}` : "./img/avatar.png"}
                size={100}
              ></Avatar>
            </div>
            <div className={style["msg"]}>
              <span className={style["name"]}>{userDetail.userName}</span>
              <div className={style["personalMsg"]}>
                <div className={style["icon"]}>
                  <FormOutlined
                    style={{
                      marginRight: "8px",
                      color: "rgba(30 ,144, 255)",
                    }}
                  />
                </div>
                <span className={style["text"]}>
                  {userDetail.userIntroduce}
                </span>
              </div>
            </div>
            <div className={style["ceateTime"]}>
              加入日期：{userDetail.createTime.split(" ")[0]}
            </div>
          </div>
          <div className={style["presonDetails"]}>
            <div className={style["title"]}>个人资料</div>
            <div className={style["content"]}>
              <BaseMsgForm
                width={500}
                options={cities}
                userDetail={userDetail}
                form={form}
                initUserInfo={initUserInfo}
              />
            </div>
          </div>
        </div>
      </div>
    </ConfigProvider>
  );
}
